package com.shj.em.aa.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shj.em.aa.entity.RoleRes;
import com.shj.em.aa.mapper.RoleResMapper;
import com.shj.em.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 角色与资源对应关系 服务实现类
 *
 * @author Shen Huang Jian
 * @since 2018-07-06
 */
@Service
@Transactional
public class RoleResServiceImpl extends ServiceImpl<RoleResMapper, RoleRes> implements RoleResService {

    @Autowired
    RoleResMapper roleresMapper;

    public void updateRoleResMappings(Long roleId, String resIds){
        Wrapper<RoleRes> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);

        if(StringUtils.isBlank(resIds)){
            roleresMapper.delete(wrapper);
        }

        List<RoleRes> roleResList = roleresMapper.selectList(wrapper);
        String[] resIdArr = resIds.split(";");

        // 删掉不在 resIdArr 中的对应关系
        List<Long> needToDelete = new ArrayList<>();
        for(RoleRes roleRes : roleResList){
            boolean flag = true;
            for(String resId : resIdArr){
                if(roleRes.getResId().toString().equals(resId)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                needToDelete.add(roleRes.getId());
            }
        }

        if(needToDelete.size() > 0){
            roleresMapper.deleteBatchIds(needToDelete);
        }

        // 添加新增的
        List<Long> needToAdd = new ArrayList<>();
        for(String resId : resIdArr){
            boolean flag = true;
            for(RoleRes ur : roleResList){
                if(ur.getResId().toString().equals(resId)){
                    flag = false;
                    break;
                }
            }
            if(flag){
                needToAdd.add(Long.parseLong(resId));
            }
        }

        for(Long resId : needToAdd){
            RoleRes roleRes = new RoleRes();
            roleRes.setRoleId(roleId);
            roleRes.setResId(resId);
            roleresMapper.insert(roleRes);
        }
    }
}
